package org.cagiobox.contactfinder;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class TestMain {

	static Logger log = Logger.getLogger(TestMain.class.getName());

	String outFilePath = "/tmp/EmailList.txt";
	List<String> f_email = new ArrayList<String>();
	List<String> g_email = new ArrayList<String>();

	public static void main(String[] args) {

		TestMain wrk = new TestMain();
		wrk.extractOpti_de();

	}

	private void extractOpti_de() {

		log.info("Start...");
		
		//TODO: estrae dalle pagine degli espositori per categoria, la lista degli espositori
		
		//Frames: 
		//  http://www.opti-mediaservices.de/prj_205/view/index.cfm?lng=1&nv=3&sb_n=products&sb1_n=prodkey&sb1=1
		
		//Sunglasses: 
		//  http://www.opti-mediaservices.de/prj_205/view/index.cfm?lng=1&nv=3&sb_n=products&sb1_n=prodkey&sb1=3
		
		
		
		
		
		
		// lista degli url alle pagine di dettaglio dei fornitori
		InputSequencer sequencer = new InputSequencer();

		List<String> f_urls = sequencer.getURLList("resources/f_links.xml");
		List<String> g_urls = sequencer.getURLList("resources/g_links.xml");

		
		//estrazione email partendo dall'url della pagina di dettaglio
		f_email = cycleExtractOpti_de(f_urls);
		g_email = cycleExtractOpti_de(g_urls);

		// write file
		PrintWriter printWriter = null;
		try {
			// Will overwrite the file if exists or creates new
			printWriter = new PrintWriter(outFilePath, "UTF-8");

			printWriter.println("Frames:");
			for (String emailaddr : f_email) {
				printWriter.println(emailaddr);
			}

			printWriter.println("Sun glasses:");
			for (String emailaddr : g_email) {
				printWriter.println(emailaddr);
			}

		} catch (FileNotFoundException fileNotFoundException) {
			fileNotFoundException.printStackTrace();
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
			unsupportedEncodingException.printStackTrace();
		} finally {
			printWriter.close();
		}

		log.info("...end.");

	}

	private List<String> cycleExtractOpti_de(List<String> urlList) {
		String baseURL_Opti_de = "http://www.opti-mediaservices.de/prj_205/view/";

		HttpClient http = new HttpClient();
		Extractor extractor = new Extractor();

		String content = null;
		String email = null;
		List<String> emails = new ArrayList<String>();

		for (String url : urlList) {

			log.info("Call url"+url);
			try {
				content = http.httpGet(baseURL_Opti_de + url);
				email = extractor.extractEmail(content);
				if (email!=null){
					log.info("Extracted:"+email);
					emails.add(email);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return emails;
	}
}
